import json
import re

from django.shortcuts import render
from .models import *
from rest_framework.views import APIView
from rest_framework.response import Response
from .ser import *
from django.core.paginator import Paginator


# Create your views here.


class NewsM(APIView):
    def post(self, request):
        ser = NewsSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 10010})

    def get(self, request):
        gain = News.objects.all()
        p = request.GET.get('page')
        page = Paginator(gain, 2)
        result = page.page(p)
        ser = NewsSer(result, many=True)
        return Response({'code': 200, 'matter': ser.data, 'tpages': page.num_pages})


class GgM(APIView):
    def post(self, request):
        gain = Ggser(data=request.data)
        if gain.is_valid():
            gain.save()
            return Response({'code': 200})
        return Response({'code': 10010})

    def get(self, request):
        gain = Gg.objects.all()
        p = request.GET.get('p')
        page = Paginator(gain, 2)
        result = page.page(p)
        ser = Ggser(result, many=True)
        return Response({'code': 200, 'matter': ser.data, 'tpages':page.num_pages})




class Text(APIView):
    def get(self, request):
        accId = '8aaf07087a331dc7017ae5ce36e83649'
        accToken = '5ea139cb96174d499534494e9489904c'
        appId = '8aaf07087a331dc7017ae5ce37be3650'
        sdk = SmsSDK(accId, accToken, appId)
        tid = '1'
        datas = (236236, 1)
        resp = sdk.sendMessage(tid, 13289792767, datas)
        result = json.loads(resp)
        if result['statusCode'] == '000000':
            return 1
        return 2


class Register(APIView):
    def post(self, request):
        # 验证用户名是否为空
        username = request.data.get('username')
        if not username:
            return Response({'code': 10010})
        # 格式是否正确
        name = re.match('\w{5,10}$', username)
        if not name:
            return Response({'code': 10011})
        # 是否唯一
        user = User.objects.first(username=username).first()
        if user:
            return Response({'code': 10012})

        # 手机号
        mobile = request.data.get('mobile')
        if not mobile:
            return Response({'code': 10013})
        mobile = re.match('/^1[3-9]d{9}$/', mobile)
        if not mobile:
            return Response({'code': 10014})
        # 是否唯一
        mobile = User.objects.first(mobile=mobile).first()
        if mobile:
            return Response({'code': 10015})

        return Response({'code': 200})
